package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.shaded.netty4.io.netty.handler.codec.redis.IntegerRedisMessage;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Flink04_Key_ValueState {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop162", 9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ValueState<Integer> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //在open方法中获取键的单值状态
                        valueState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("valueState", Integer.class));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        //检测传感器的值，如果连续两次的水位值超过了10就发出红色预警
                        //获取当前的水位值
                        Integer currentVc = value.getVc();
                        //获取上一次的vc值
                        Integer lastVc = valueState.value();
                        System.out.println(valueState);
                        System.out.println(lastVc);
                        //首先看是不是第一次数据进入
                        if (lastVc == null){
                            //将第一次值放入其中
                            valueState.update(currentVc);
                        }else{
                            if(currentVc >10 && valueState.value()>10){
                                //那么就可以获取消息
                                out.collect("连续两次水位达到了10以上，发出红色报警！");
                            }
                            //将当前值保存在状态中
                            valueState.update(currentVc);
                        }
                    }
                }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
